package com.quyunshuo.module.home.activity.history

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.activity.help.HelpAppTitle
import com.quyunshuo.module.home.fragment.me.Resource
import com.quyunshuo.module.home.room.entity.ConcentrationEntity

//写法二：使用flow，返回的是一个 Room 的 Flow，Room 会自动在底层数据变化时（增删改）重新发出新的数据，减少多余代码。
@Composable
fun HistoryPageFlow(viewModel: HistoryViewModel = viewModel()) {
    val dataAll by viewModel.dataAllFlow.collectAsState()
    Column(
        Modifier
            .fillMaxSize()
            .background(colorResource(R.color.line_color))
    ) {
        HelpAppTitle(R.string.home_history_title)
        val data = dataAll
        if (data.isEmpty()) {
        } else {
            // 显示历史记录列表 这样层层传递好吗？算是比较好的了，提高可维护性和可测试性
            HistoryList(data = data) {
                viewModel.deleteById(it)
            }
        }
    }
}

// 非flow版本。
@Composable
fun HistoryPage(viewModel: HistoryViewModel = viewModel()) {
    val historyState by viewModel.dataAll.collectAsState()
    Column(
        Modifier
            .fillMaxSize()
            .background(colorResource(R.color.line_color))
    ) {
        HelpAppTitle(R.string.home_history_title)
        when (historyState) {
            is Resource.Error -> {
            }

            Resource.Loading -> {}
            is Resource.Success<List<ConcentrationEntity>> -> {
                val data = (historyState as Resource.Success).data
                if (data.isEmpty()) {
                } else {
                    // 显示历史记录列表 这样层层传递好吗？算是比较好的了，提高可维护性和可测试性
                    HistoryList(data = data) {
                        viewModel.deleteById(it)
                    }
                }
            }
        }
    }
}

@Composable
fun HistoryList(
    data: List<ConcentrationEntity>,
    deleteClback: (Long) -> Unit
) {
    var isDelete by remember { mutableStateOf(false) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var id:Long = -1

    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(16.dp)
    ) {
        if (isDelete) {
            item {
                Row(
                    modifier = Modifier.padding(10.dp)
                ) {
                    Text("全部删除")
                    Spacer(modifier = Modifier.weight(1f))
                    Text("取消", modifier = Modifier.clickable {
                        isDelete = false
                    })
                }
            }
        } else {
            item {
                Row(
                    modifier = Modifier.padding(10.dp)
                ) {
                    Spacer(modifier = Modifier.weight(1f))
                    Image(
                        painter = painterResource(if (isDelete) R.drawable.delete_sel else R.drawable.delete_no),
                        contentDescription = null,
                        modifier = Modifier
                            .size(20.dp)
                            .clickable {
                                isDelete = !isDelete

                            })
                }
            }
        }


        items(data) { item ->
            HistoryItem(
                entity = item,
                isDelete = isDelete,
                deleteClback = {
                    showDeleteDialog = true
                    id = it
                }
            )
        }
        item {
            if (showDeleteDialog){
                //点击的时候，修改isdelete
                AlertDialogExample{
                    if (id!= (-1).toLong()) {
                        if (it)deleteClback.invoke(id)
                    }
                    showDeleteDialog = false

                }
            }
        }
    }
}

@Composable
fun AlertDialogExample(isDelete:(Boolean)->Unit) {
    // 1. 创建控制对话框显示的状态
    var showDialog by remember { mutableStateOf(true) }

    // 3. 条件显示对话框
    if (showDialog) {
        AlertDialog(
            onDismissRequest = {
                // 4. 关闭对话框的方式一：点击外部或按返回键
                showDialog = false
            },
            title = { Text("提醒") },
            text = { Text("是否确定删除？") },
            confirmButton = {
                Button(onClick = {
                    // 5. 关闭对话框的方式二：点击确认按钮
                    showDialog = false
                    isDelete.invoke(true)
                }) {
                    Text("确定")
                }
            },
            dismissButton = {
                Button(onClick = {
                    // 6. 关闭对话框的方式三：点击取消按钮
                    showDialog = false
                    isDelete.invoke(false)

                }) {
                    Text("取消")
                }
            }
        )
    }
}

@Composable
fun HistoryItem(
    entity: ConcentrationEntity,
    isDelete: Boolean,
    deleteClback: (Long) -> Unit
) {
    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(60.dp)
                .background(color = colorResource(R.color.white), RoundedCornerShape(20.dp))
                .padding(horizontal = 20.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Box(
                modifier = Modifier
                    .size(30.dp)
                    .background(
                        color = Color(0x3303A9F4),
                        RoundedCornerShape(30.dp)
                    )
                    .padding(5.dp)
            ) {
                Image(/*为什么image会预览有问题？图片为什么不行呢？？？刷新一下。*/
                    painter = painterResource(R.drawable.history_sleep),
                    contentDescription = null,
                    modifier = Modifier.size(20.dp)
                )
            }
            Spacer(modifier = Modifier.width(10.dp))

            Column {
                Text("睡眠")
                Text(entity.focusDate, color = colorResource(R.color.color_2E2E2E))
            }
            Spacer(modifier = Modifier.weight(1f))
            Box {
                if (isDelete) {
                    Image(
                        painter = painterResource(R.drawable.delete_sel), contentDescription = null,
                        modifier = Modifier
                            .size(20.dp)
                            .clickable {
                                //删除一条数据，然后刷新一下列表。
                                deleteClback.invoke(entity.id)
                            })
                } else {
                    Text(
                        "${entity.durationMinutes} 分钟",
                        color = colorResource(R.color.color_2E2E2E)
                    )

                }
            }


        }
        Spacer(Modifier.height(10.dp))
    }

}

@Preview
@Composable
fun HistoryPagePreview() {
    Column {
        HelpAppTitle(R.string.home_history_title)
        HistoryList(listOf(ConcentrationEntity(), ConcentrationEntity()), {})
    }

}